package com.springfreemwork.proxy.cglib;


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author gpo12345678@163.com
 * @create 2024-04-07 15:39
 */
public class CglibProxy {
	public static void main(String[] args) {
		// 创建动态代理
		SampleClass sampleClass = (SampleClass) getCglibProxy(SampleClass.class);
		sampleClass.sampleMethod();
	}

	public static Object getCglibProxy(Class<?> clazz) {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(clazz);
		enhancer.setCallback(new MethodInterceptor() {
			@Override
			public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
				System.out.println("Before method invocation: " + method.getName());
				Object result = methodProxy.invokeSuper(o, objects);
				System.out.println("After method invocation: " + method.getName());
				return result;
			}
		});
		return enhancer.create();
	}

	static class SampleClass {
		public void sampleMethod() {
			System.out.println("Sample method has been called");
		}
	}
}
